﻿using System.Security.Principal;
using System.Web;
using IterationLife.System.Repositories;
using Microsoft.Ajax.Utilities;
using Util;
using Util.Domains.Contexts;
using Util.Helpers;
using Util.Security;
using Util.Webs.Security;

namespace IterationLife.DataService.ApiServices.Authentication
{
    /// <summary>
    /// 身份认证模块
    /// </summary>
    public class AuthenticationModule : AuthenticateModuleBase {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private IUserRepository _userRepository;



        /// <summary>
        /// 认证前操作
        /// </summary>
        protected override bool AuthenticateBefore( HttpApplication application ) {
            base.AuthenticateBefore( application );
            //_userRepository = Ioc.Create<IUserRepository>();

            //var user = _userRepository.Single( t => t.UserName == "Administrator");
            //SecurityHelper.SignIn( user.Id.ToString() );
            return true;
        }

        /// <summary>
        /// 获取安全令牌名称
        /// </summary>
        protected override string GetTokenName() {
            return "Authorization";
        }

        /// <summary>
        /// 通过安全令牌获取用户编号
        /// </summary>
        /// <param name="application">Http应用程序</param>
        /// <param name="token">安全令牌</param>
        protected override IPrincipal GetPrincipalByToken( HttpApplication application, string token )
        {
            string userId = token;
            if(userId.IsNullOrWhiteSpace())
                return UnauthenticatedPrincipal.Instance;
            return GetPrincipal(userId);
        }

        /// <summary>
        /// 创建应用程序上下文
        /// </summary>
        /// <param name="userId">用户编号</param>
        protected override IUserContext CreateUserContext( string userId ) {
            if( userId.IsEmpty() )
                return NullUserContext.Instance;
            UserContext result = new UserContext( true, userId, Net.Ip, Net.Host, Net.Browser );
            return result;
        }



    }
}
